package com.back.service.impl;

import com.back.domain.VO.SysDeptVO;
import com.back.domain.VO.SYSTEM.SysDeptTreeNode;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.back.domain.SysDept;
import com.back.service.SysDeptService;
import com.back.mapper.SysDeptMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author 陈胜杰
* @description 针对表【sys_dept(组织机构)】的数据库操作Service实现
* @createDate 2024-07-12 10:22:00
*/
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept>
    implements SysDeptService{
        @Autowired
    public SysDeptMapper sysDeptMapper;

    @Override
    public SysDeptTreeNode buildTree() throws JsonProcessingException {
        List<SysDeptVO> data = sysDeptMapper.sysDeptGetAll();
        List<String[]> stringData = data.stream()
                .map(SysDeptVO::toRow)
                .collect(Collectors.toList());
//        TreeNode root = buildTreeUtil(stringData);
//        ObjectMapper mapper = new ObjectMapper();
        Map<Integer, SysDeptTreeNode> nodeMap = new HashMap<>();
        SysDeptTreeNode root = null;

        for (String[] row : stringData) {
            int id = Integer.parseInt(row[0]);
            String name = row[1];
            int parentId = Integer.parseInt(row[2]);

            SysDeptTreeNode node = new SysDeptTreeNode();
            node.setId(id);
            node.setName(name);

            nodeMap.put(id, node);

            if (parentId == 0) {
                root = node;
            } else {
                SysDeptTreeNode parent = nodeMap.get(parentId);
                if (parent != null) {
                    parent.addChild(node);
                }
            }
        }

        return root;
    }
}




